<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Travel as TravelModel;
use think\Db;
use app\common\library\SearchLog;

/**
 * 文旅信息接口
 * @ApiWeigh (83)
 */
class Travel extends Api
{
    protected $noNeedLogin = ['index', 'detail'];
    protected $noNeedRight = '*';


    /**
     * 文旅分类列表
     * 
     * @ApiTitle    (文旅分类列表)
     * @ApiSummary  (获取文旅信息分类列表)
     * @ApiMethod   (GET)
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "success",
     *   "data": [{
     *     "id": 1,
     *     "name": "分类名称",
     *     "image": "分类图片"
     *   }]
     * })
     */
    public function category()
    {
        $list = \app\common\model\TravelCategory::where('status', 1)
            ->field('id,name,image')
            ->order('weigh DESC,id DESC')
            ->select();
            
        // 处理图片路径
        foreach($list as &$item) {
            $item['image'] = cdnurl($item['image']);
        }
            
        $this->success('', $list);
    }

    /**
     * 文旅信息列表
     * 
     * @ApiTitle    (文旅信息列表)
     * @ApiSummary  (获取文旅信息列表，支持分页、搜索、分类筛选和排序)
     * @ApiMethod   (GET)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default=1)
     * @ApiParams   (name="per_page", type="integer", required=false, description="每页数量", default=10)
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词")
     * @ApiParams   (name="category_id", type="integer", required=false, description="分类ID", default=0)
     * @ApiParams   (name="order_field", type="string", required=false, description="排序字段:weigh=默认,sales=销量,price=价格,time=发布时间", default="weigh")
     * @ApiParams   (name="order_type", type="string", required=false, description="排序方向:desc=降序,asc=升序", default="desc")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": 100,                     // 总记录数
          "per_page": 10,                   // 每页数量
          "current_page": 1,                // 当前页码
          "last_page": 10,                  // 最后一页页码
          "data": [{
            "id": 1,                        // 文旅信息ID
            "title": "标题",                // 标题
            "image": "封面图",              // 封面图片
            "price": "19.90",               // 价格
            "sales": 100,                   // 销量
            "address": "地址",              // 地址
            "category_id": 1,               // 分类ID
            "category": {                   // 分类信息
              "id": 1,
              "name": "分类名称",
              "image": "分类图片"
            }
          }]
        }
      })
     */
    public function index()
    {
        $page = $this->request->get('page', 1);
        $per_page = $this->request->get('per_page', 10);
        $keyword = $this->request->get('keyword', '');
        $category_id = $this->request->get('category_id', 0);
        $sort = $this->request->get('sort', '');

        $where = ['status' => 1];
        if ($keyword) {
            $where[] = function($query) use ($keyword) {
                $query->where('title', 'like', "%{$keyword}%")
                    ->whereOr('description', 'like', "%{$keyword}%");
            };
            
            // 记录搜索历史
            if ($this->auth->id) {
                SearchLog::record($this->auth->id, $keyword, 'travel');
            }
        }
        
        // 分类筛选
        if ($category_id) {
            $where['category_id'] = $category_id;
        }

        $query = TravelModel::with(['category'])->where($where)
            ->field('id,title,image,price,sales,address,category_id');
            
        // 排序方式
        $orderField = $this->request->get('order_field', 'weigh');
        $orderType = $this->request->get('order_type', 'desc');
        
        // 允许的排序字段
        $allowFields = [            'weigh' => 'weigh',
            'sales' => 'sales',
            'price' => 'price',
            'time' => 'createtime'
        ];
        
        // 验证排序字段和方向
        $field = isset($allowFields[$orderField]) ? $allowFields[$orderField] : 'weigh';
        $type = strtolower($orderType) === 'asc' ? 'ASC' : 'DESC';
        
        $query->order($field . ' ' . $type . ', id DESC');
        
        $list = $query->page($page, $per_page)->select();
        
        // 处理图片完整路径
        foreach($list as &$item) {
            $item['image'] = cdnurl($item['image']);
            if(isset($item['category']) && !empty($item['category'])) {
                $item['category']['image'] = cdnurl($item['category']['image']);
            }
        }
        $total =  TravelModel::with(['category'])->where($where)->count();
        $this->success('', [
            'total' => $total,
            'per_page' => $per_page,
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'data' => $list
        ]);
    }

   /**
     * 文旅信息详情
     * 
     * @ApiTitle    (文旅信息详情)
     * @ApiSummary  (获取文旅信息详细内容)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="文旅信息ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "id": 1,                        // 文旅信息ID
          "title": "标题",                // 标题
          "image": "封面图",              // 封面图片
          "images": ["图片1","图片2"],    // 轮播图列表
          "price": "19.90",               // 价格
          "sales": 100,                   // 销量
          "address": "地址",              // 地址
          "phone": "联系电话",            // 联系电话
          "business_hours": "营业时间",   // 营业时间
          "description": "详细介绍",      // 详细介绍
          "instructions": "使用说明",     // 使用说明
          "category_id": 1,               // 分类ID
          "category": {                   // 分类信息
            "id": 1,
            "name": "分类名称",
            "image": "分类图片"
          }
        }
      })
     */
    public function detail()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数错误');
        }

        $info = TravelModel::where(['id' => $id, 'status' => 1])->find();
        if (!$info) {
            $this->error('信息不存在');
        }
        
        // 处理图片完整路径
        $info['image'] = cdnurl($info['image']);
        if(!empty($info['images'])) {
            $info['images'] = array_map('cdnurl', $info['images']);
        }
        $category = Db::name('travel_category')->where(['id' => $info['category_id'], 'status' => 1])->find();
        if($category) {
            $category['image'] = cdnurl($category['image']);
        }
        $info['category'] = $category;
        // if(isset($info['category'])) {
        //     $info['category']['image'] = isset($info['category']['image']) ? cdnurl($info['category']['image']) : '';
        // }
       
        $this->success('', $info);
    }

    /**
     * 创建订单
     * 
     * @ApiTitle    (创建文旅订单)
     * @ApiSummary  (创建文旅信息预订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="travel_id", type="integer", required=true, description="文旅信息ID")
     * @ApiParams   (name="num", type="integer", required=true, description="预订数量", minimum=1)
     * @ApiParams   (name="name", type="string", required=true, description="收货人姓名")
     * @ApiParams   (name="phone", type="string", required=true, description="收货人电话")
     * @ApiParams   (name="address", type="string", required=true, description="收货地址")
     * @ApiReturn   ({
            "code": 1,
            "msg": "success",
            "data": {
                "order_no": "202401011234567890",    // 订单编号
                "title": "标题",                      // 商品标题
                "price": "19.90",                     // 单价
                "num": 1,                             // 购买数量
                "total_price": "19.90",               // 总价
                "name": "张三",                       // 收货人姓名
                "phone": "13800138000",               // 联系电话
                "address": "收货地址"                 // 收货地址
            }
        })
     */
    public function createOrder()
    {
        $travel_id = $this->request->post('travel_id');
        $num = $this->request->post('num/d', 1);
        $name = $this->request->post('name');
        $phone = $this->request->post('phone');
        $address = $this->request->post('address');
        $remark = $this->request->post('remark');
        
        // 参数验证
        if (!$travel_id || $num < 1 || !$name || !$phone || !$address) {
            $this->error('请完善收货信息');
        }

        $travel = TravelModel::where(['id' => $travel_id, 'status' => 1])->find();
        if (!$travel) {
            $this->error('文旅信息不存在');
        }

        // 生成订单号
        $order_no = date('YmdHis') . rand(1000, 9999);
        
        // 创建订单
        $order = \app\common\model\TravelOrder::create([
            'order_no' => $order_no,
            'user_id' => $this->auth->id,
            'travel_id' => $travel_id,
            'title' => $travel->title,
            'price' => $travel->price,
            'remark' => $remark,
            'num' => $num,
            'total_price' => bcmul($travel->price, $num, 2),
            'name' => $name,
            'phone' => $phone,
            'address' => $address,
            'status' => \app\common\model\TravelOrder::STATUS_UNPAID
        ]);

        $this->success('', [
            'order_no' => $order->order_no,
            'order_id' => $order->id,
            'title' => $order->title,
            'price' => $order->price,
            'num' => $order->num,
            'total_price' => $order->total_price,
            'name' => $order->name,
            'phone' => $order->phone,
            'address' => $order->address
        ]);
    }

    /**
     * 订单列表
     * 
     * @ApiTitle    (文旅订单列表)
     * @ApiSummary  (获取用户文旅订单列表)
     * @ApiMethod   (GET)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default=1)
     * @ApiParams   (name="per_page", type="integer", required=false, description="每页数量", default=10)
     * @ApiParams   (name="status", type="string", required=false, description="订单状态:0=待支付,1=已支付,2=已发货,3=已完成,4=已取消",全部=all"")
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词,支持订单号/商品标题")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "total": 100,                     // 总记录数
          "per_page": 10,                   // 每页数量
          "current_page": 1,                // 当前页码
          "last_page": 10,                  // 最后一页页码
          "data": [{
            "id": 1,                        // 订单ID
            "order_no": "T202401010001",    // 订单号
            "title": "标题",                // 商品标题
            "image": "封面图",              // 商品图片
            "price": "19.90",               // 单价
            "num": 1,                       // 购买数量
            "total_price": "19.90",         // 总价
            "name": "张三",                 // 收货人姓名
            "phone": "13800138000",         // 联系电话
            "address": "收货地址",          // 收货地址
            "status": 1,                    // 订单状态:0=已取消,1=待支付,2=已支付,3=已完成
            "createtime": "2024-01-01 00:00:00"  // 创建时间
          }]
        }
      })
     */
    public function orderList()
    {
        $page = $this->request->get('page', 1);
        $per_page = $this->request->get('per_page', 10);
        $params = $this->request->get();
        $keyword = $this->request->get('keyword', '');

        $where = [
            'user_id' => $this->auth->id,
            'deletetime' => null
        ];
        
        // 状态筛选
        if($params['status'] != 'all' && $params['status'] !== null && $params['status']!== ''){
            $where['status'] = ['=', intval($params['status'])];
        }
        
        // 关键词搜索
        if($keyword){
            $where[] = function($query) use ($keyword) {
                $query->where('order_no', 'like', "%{$keyword}%")
                    ->whereOr('title', 'like', "%{$keyword}%");
            };
            
            // 记录搜索历史
            SearchLog::record($this->auth->id, $keyword, 'travel_order');
            
        }

        $query = \app\common\model\TravelOrder::alias('o')->where($where);
        $list = $query->field([
            'id',
            'travel_id',
            'order_no',
            'title',
            'price',
            'num', 
            'total_price',
            'name',
            'phone',
            'address',
            'status',
            'createtime'
        ])->page($page, $per_page)->order('id desc')->select();
        
        $total = \app\common\model\TravelOrder::where($where)->count();
        
        // 处理图片完整路径
        foreach($list as &$item) {
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
            $travel = Db::name('travel')->where('id', $item['travel_id'])->find();
            if($travel) {
                $item['image'] = cdnurl($travel['image']);
            }else{
                $item['image'] = '';
            }
        }

        $this->success('', [
            'total' => $total,
            'per_page' => $per_page,
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'data' => $list
        ]);
    }

    /**
     * 订单详情
     * 
     * @ApiTitle    (文旅订单详情)
     * @ApiSummary  (获取文旅订单详细信息)
     * @ApiMethod   (GET)
     * @ApiParams   (name="order_no", type="string", required=true, description="订单号")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "id": 1,                          // 订单ID
          "order_no": "T202401010001",      // 订单号
          "title": "标题",                  // 商品标题
          "price": "19.90",                 // 单价
          "num": 1,                         // 数量
          "total_price": "19.90",           // 总价
          "name": "张三",                   // 收货人
          "phone": "13800138000",           // 联系电话
          "address": "收货地址",            // 收货地址
          "status": 1,                      // 订单状态
          "pay_time": null,                 // 支付时间
          "createtime": "2024-01-01 00:00:00",  // 创建时间
          "pay_end_time": null,              // 支付截止时间
          "travel": {                       // 文旅信息
            "id": 1,
            "title": "标题",
            "image": "封面图"
          }
        }
      })
     */
    public function orderDetail()
    {
        $order_no = $this->request->get('order_no');
        if (!$order_no) {
            $this->error('参数错误');
        }

        $order = \app\common\model\TravelOrder::with(['travel'])
            ->where(['order_no' => $order_no, 'user_id' => $this->auth->id])
            ->find();
            
        if (!$order) {
            $this->error('订单不存在');
        }
        
        // 处理图片完整路径和时间格式化
        if ($order->travel) {
            $order->travel->image = cdnurl($order->travel->image);
        }
        
        // 整理返回数据
        $result = [
            'id' => $order->id,
            'order_no' => $order->order_no,
            'title' => $order->title,
            'price' => $order->price,
            'num' => $order->num,
            'total_price' => $order->total_price,
            'name' => $order->name,
            'phone' => $order->phone,
            'address' => $order->address,
            'remark' => $order->remark,
            'status' => $order->status,
            'pay_time' => $order->pay_time ? date('Y-m-d H:i:s', $order->pay_time) : null,
            'ship_time' => $order->ship_time ? date('Y-m-d H:i:s', $order->ship_time) : null,
            'complete_time' => $order->complete_time ? date('Y-m-d H:i:s', $order->complete_time) : null,
            'createtime' => date('Y-m-d H:i:s', $order->createtime),
            'pay_end_time' => $order->status == 0 ? ($order->createtime + 7200) : null,  // 未支付状态下返回最后支付时间
            'travel' => $order->travel ? [
                'id' => $order->travel->id,
                'title' => $order->travel->title,
                'image' => $order->travel->image
            ] : null
        ];

        $this->success('', $result);
    }

    /**
     * 订单支付
     * 
     * @ApiTitle    (订单支付)
     * @ApiSummary  (发起文旅订单支付)
     * @ApiMethod   (POST)
     * @ApiParams   (name="order_no", type="string", required=true, description="订单编号")
     * @ApiParams   (name="pay_type", type="string", required=true, description="支付方式:wechat=微信支付,alipay=支付宝支付")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "type": "wechat",      // 支付方式
          "params": {}           // 支付参数
        }
      })
     */
    public function payment()
    {
        $orderNo = $this->request->post('order_no');
        $payType = $this->request->post('pay_type');
        
        // 验证支付方式
        if (!in_array($payType, ['wechat', 'alipay'])) {
            $this->error('不支持的支付方式');
        }
        
        $order = \app\common\model\TravelOrder::where([
            'order_no' => $orderNo,
            'user_id' => $this->auth->id,
            'status' => \app\common\model\TravelOrder::STATUS_UNPAID
        ])->find();

        if (!$order) {
            $this->error('订单不存在或已支付');
        }
        if($order->total_price <= 0){
            $this->error('订单金额错误');
        }
        try {
            // 创建支付
            $notify_url = request()->domain() . '/api/payment/notifyTravel/paytype/' . $payType;
            $result = \addons\epay\library\Service::submitOrder($order->total_price, $order->order_no, 
                $payType, '文旅订单', $notify_url, '','app');
                
            if (!$result) {
                $this->error('创建支付失败');
            }
            
            $this->success('', [
                'type' => $payType,
                'params' => $payType == 'wechat' ? json_decode($result, true) : $result
            ]);
        } catch (\think\exception\PDOException $e) {
            $this->error('支付失败：' . $e->getMessage());
        }
    }

    /**
     * 取消订单
     * 
     * @ApiTitle    (取消文旅订单)
     * @ApiSummary  (取消未支付的文旅订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "取消成功",
        "data": null
      })
     */
    public function cancelOrder()
    {
        $id = $this->request->post('id');
        
        $order = \app\common\model\TravelOrder::where([
            'id' => $id,
            'user_id' => $this->auth->id,
            'status' => \app\common\model\TravelOrder::STATUS_UNPAID
        ])->find();

        if (!$order) {
            $this->error('订单不存在或无法取消');
        }

        Db::startTrans();
        try {
            // 更新订单状态为已取消
            $order->status = \app\common\model\TravelOrder::STATUS_CANCEL;
            $order->save();
            
            // 创建系统消息
            \app\common\model\SystemMessage::create([
                'user_id' => $order->user_id,
                'type' => 'travel',
                'title' => '订单已取消',
                'content' => "您的文旅订单 {$order->order_no} 已取消",
                'order_id' => $order->id,
                'order_no' => $order->order_no
            ]);

            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error('取消订单失败');
        }

        $this->success('取消成功');
    }

    /**
     * 确认收货
     * 
     * @ApiTitle    (确认收货)
     * @ApiSummary  (确认收货并完成文旅订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "确认收货成功",
        "data": null
      })
     */
    public function confirmOrder()
    {
        $id = $this->request->post('id');
        
        $order = \app\common\model\TravelOrder::where([
            'id' => $id,
            'user_id' => $this->auth->id,
            'status' => \app\common\model\TravelOrder::STATUS_SHIPPED
        ])->find();

        if (!$order) {
            $this->error('订单不存在或无法确认收货');
        }

        Db::startTrans();
        try {
            // 更新订单状态为已完成
            $order->status = \app\common\model\TravelOrder::STATUS_FINISH;
            $order->complete_time = time();
            $order->save();
            
            // 创建系统消息
            \app\common\model\SystemMessage::create([
                'user_id' => $order->user_id,
                'type' => 'travel',
                'title' => '订单已完成',
                'content' => "您的文旅订单 {$order->order_no} 已确认收货，感谢您的购买！",
                'order_id' => $order->id,
                'order_no' => $order->order_no
            ]);

            Db::commit();
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error('确认收货失败');
        }

        $this->success('确认收货成功');
    }

    /**
     * 删除订单
     * 
     * @ApiTitle    (删除文旅订单)
     * @ApiSummary  (删除已完成或已取消的文旅订单)
     * @ApiMethod   (POST)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "删除成功",
        "data": null
      })
     */
    public function deleteOrder()
    {
        $id = $this->request->post('id');
        
        $order = \app\common\model\TravelOrder::where([
            'id' => $id,
            'user_id' => $this->auth->id,
            'deletetime' => null
        ])->where('status', 'in', [\app\common\model\TravelOrder::STATUS_FINISH, \app\common\model\TravelOrder::STATUS_CANCEL])
        ->find();

        if (!$order) {
            $this->error('订单不存在或无法删除');
        }

        // 软删除订单
        $order->deletetime = time();
        if ($order->save()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    /**
     * 查询物流信息
     * 
     * @ApiTitle    (查询物流信息)
     * @ApiSummary  (根据订单ID查询物流跟踪信息)
     * @ApiMethod   (GET)
     * @ApiParams   (name="id", type="integer", required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "success",
        "data": {
          "express_company": "顺丰快递",  // 物流公司
          "express_no": "SF123456789",   // 物流单号
          “address”: "收货地址",         // 收货地址
          "contact": "收货人姓名",        // 收货人姓名
          "phone": "联系电话",          // 联系电话
          "list": [{                     // 物流轨迹
            "time": "2024-01-01 12:00:00",  // 时间
            "context": "已签收"             // 物流状态描述
          }]
        }
      })
     */
    public function express()
    {
        $id = $this->request->get('id');
        
        $order = \app\common\model\TravelOrder::where([
            'id' => $id,
            'user_id' => $this->auth->id,
            'status' => ['in', [2,3]] // 已发货或已完成
        ])->find();

        if (!$order) {
            $this->error('订单不存在或未发货');
        }

        if (empty($order->express_no) || empty($order->express_code)) {
            $this->error('物流信息不存在');
        }

        try {
            $expModle = new \addons\expressquery\library\Expressquery();
            
            $list = $expModle->getExpressList($order->express_code, $order->express_no);

            $this->success('', [
                'express_company' => $order->express_company,
                'express_no' => $order->express_no,
                'address' => $order->address,      // 收货地址
                'contact' => $order->name,         // 收货人
                'phone' => $order->phone,          // 联系电话
                'list' => $list
            ]);
            
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        }
    }
}
